<template>
  <u-popup v-model="show" @close="close" @open="open" :mode="mode" :length="popupLength" :mask="mask"
    :closeable="closeable" :close-icon-pos="closeIconPos" height="60%">
    <view class="popup">
      <view class="popup-hd">
        请选择系统用户<text class="primary">（已选 {{this.selectedData.length}}个）</text>
      </view>
      <view class="popup-bd">
        <scroll-view :scroll-top="scrollRightTop" scroll-y="true" scroll-with-animation>
          <view class="user-group-list">
            <view v-for="(item, index) in data" :key="index" :id="'item' + index" class="user-group-item">
              <view class="user-group-title">{{item.deptName}}</view>
              <view class="user-list">
                <view v-for="(it, idx) in item.userList" :key="idx" :id="'item' + idx" class="user-item">
                  <u-checkbox v-model="it.checked" :name="it.id" @change="userChange">{{it.name}}</u-checkbox>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="popup-ft">
        <view class="button" @click="submit">确认</view>
        <view v-if="showClearBtn" class="button danger" @click="clearAll">清空</view>
        <view v-if="showCloseBtn" class="button" @click="close">取消</view>
      </view>
    </view>
  </u-popup>
</template>
<script>
  export default {
    name: "JsPopup",
    props: {
      // 模式
      mode: {
        type: String,
        default: 'bottom'
      },
      lengthProp: {
        type: String,
        default: '60%'
      },
      // 是否显示遮罩
      mask: {
        type: Boolean,
        default: true
      },
      // 是否可以关闭
      closeable: {
        type: Boolean,
        default: false
      },
      closeIconPos: {
        type: String,
        default: 'top-right'
      },
      defaultVaule: {
        type: Array,
        default () {
          return [];
        }
      },
      action: {
        type: String,
        default: ''
      },
      multiple: {
        type: Boolean,
        default: false
      },
      // 默认已选的用户列表
      defaultSelectedUserList: {
        type: Array,
        default () {
          return [];
        }
      },
      // 是否显示清除按钮
      showClearBtnProp: {
        type: Boolean,
        default: true
      },
      // 是否显示关闭按钮
      showCloseBtnProp: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        scrollTop: 0, //tab标题的滚动条位置
        oldScrollTop: 0,
        current: 0, // 预设当前项的值
        menuHeight: 0, // 左边菜单的高度
        menuItemHeight: 0, // 左边菜单item的高度
        itemId: '', // 栏目右边scroll-view用于滚动的id
        data: null,
        menuItemPos: [],
        arr: [],
        scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
        timer: null, // 定时器
        tagShow: false,
        show: false,
        keywords: '',
        selectedData: [],
        allData: [],
        popupLength: this.lengthProp,
        showClearBtn: this.showClearBtnProp,
        showCloseBtn: this.showCloseBtnProp,
      }
    },
    onLoad() {

    },
    watch: {

    },
    created() {
      if (this.action != null && this.action != '') {
        this.$u.api.getUrlData(this.action, {}).then(res => {
          if (!res.data || res.data.length == 0) {
            return;
          }
          res.data.forEach((item) => {
            item.checked = false;
            item.userList.forEach((it) => {
              it.checked = false;
            })
          })
          this.data = res.data;
          this.allData = res.data;
          this.setDefaultSelectedUserList(this.defaultSelectedUserList);
        });
      }
    },
    mounted() {
      this.$nextTick(() => {
        // 监听当前实例上的自定义事件 remove-selected-user-by-id
        this.$on('remove-selected-user-by-id', (id) => {
          this.doUnSelectDataById(id);
        })
      });
    },
    onReady() {

    },
    destroyed() {
      // console.log('组件js-choose-user-popup实例销毁', this);
    },
    methods: {
      close() {
        this.show = false;
        this.$emit('close');
      },
      open() {
        this.show = true;
      },
      setDefaultVal(val) {
        this.data.forEach((item) => {
          item.checked = false;
        })
        val.forEach((item) => {
          this.data.forEach((userItem) => {
            if (item.id == userItem.id) {
              userItem.checked = true;
              return;
            }
          })
        })
        this.setSelectedData();
      },
      setSelectedData() {
        let selectData = [];
        this.allData.forEach((item) => {
          item.userList.forEach((it) => {
            if (it.checked && it.dataType != 1) {
              selectData.push(it);
            }
          })
        })
        this.selectedData = selectData;
      },
      orgChange(e) {
        this.data.forEach((item) => {
          if (item.id === e.name) {
            item.userList.forEach((it) => {
              it.checked = e.value;
            })
          }
        })
        this.setSelectedData();
      },
      userChange(e) {
        this.data.forEach((item) => {
          item.userList.forEach((it) => {
            if (it.id === e.name) {
              it.checked = e.value;
            }
          })
        })
        if (!this.multiple && e.value) {
          this.handleSingleSelectMode(e.name);
        }
        this.setSelectedData();
      },
      /**
       * 处理单选模式
       * @param {Object} id 用户ID
       */
      handleSingleSelectMode(id) {
        //取消其他已勾选的项
        this.data.forEach((item) => {
          item.userList.forEach((it) => {
            if (it.id !== id) {
              it.checked = false;
            }
          })
        })
      },
      tagClick(row) {
        this.data.forEach((item) => {
          if (row.id == item.id) {
            item.checked = false;
          }
        })
        this.setSelectedData();
      },
      clearAll() {
        this.data.forEach((item) => {
          item.checked = false;
          item.userList.forEach((it) => {
            it.checked = false;
          })
        })
        this.selectedData = [];
      },
      submit() {
        this.$emit('submit');
      },
      getData() {
        return this.selectedData;
      },
      search(value) {
        if (value != null && value !== '' && value != undefined) {
          this.data = this.data.filter(item => item.account.includes(value) || item.name.includes(value));
        } else {
          this.data = this.allData;
        }
      },
      setDefaultSelectedUserList(defaultSelectedUserList) {
        if (defaultSelectedUserList.length == 0) {
          return;
        }
        this.data.forEach((item) => {
          item.userList.forEach((user) => {
            let isDefault = defaultSelectedUserList.some(defaultUser => defaultUser.id == user.id);
            if (isDefault) {
              user.checked = true;
            }
          })
        })
        this.setSelectedData();
      },
      /**
       * 根据指定id剔除已选数据
       * @param {Object} id
       */
      doUnSelectDataById(id) {
        this.data.forEach((item) => {
          item.userList.forEach((it) => {
            if (it.id === id) {
              it.checked = false;
            }
          })
        })
        this.setSelectedData();
      }
    }
  }
</script>

<style lang="scss" scoped>
  .u-drawer {
    /deep/ .u-drawer-content {
      border-radius: 40rpx 40rpx 0 0;
      padding-top: 40rpx;
      background: #fff;
    }
  }

  .popup {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .popup-hd {
    padding: 0 32rpx;
    margin-bottom: 32rpx;
    font-size: 32rpx;
    font-weight: 700;
    color: #333;

    .primary {
      color: #3989FC;
    }
  }

  .popup-bd {
    flex: 1;
    overflow: hidden;
  }

  .popup-ft {
    display: flex;
    padding: 0 32rpx 24rpx;

    .button {
      flex: 1;
      height: 96rpx;
      border-radius: 96rpx;
      line-height: 96rpx;
      text-align: center;
      font-size: 32rpx;
      font-weight: 500;
      color: #fff;
      background: #3989FC;

      &+.button {
        margin-left: 24rpx;
        color: #fff;
        background: #D43030;
      }
    }
  }

  .user-group-item {
    padding: 0 32rpx 40rpx;
  }

  .user-group-title {
    position: relative;
    line-height: 40rpx;
    font-size: 28rpx;
    font-weight: 700;
    color: #333;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -32rpx;
      display: inline-block;
      width: 6rpx;
      height: 40rpx;
      border-radius: 0 6rpx 6rpx 0;
      background: #1676FE;
    }
  }

  .user-item {
    border-bottom: 1px solid #eee;
    padding: 24rpx 0;

    /deep/ .u-checkbox__icon-wrap {
      border-radius: 50%;

      &.u-checkbox__icon-wrap--checked {
        background: #1676FE;
      }
    }

    /deep/ .u-checkbox__label {
      margin: 0 16rpx;
      font-size: 28rpx;
      font-weight: 500;
      color: #999;
    }
  }
</style>